package com.mytomcat.catalina.server;

import com.mytomcat.catalina.lifecycle.LifeCycleBase;
import com.mytomcat.catalina.service.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 标准server
 *
 * @author supu
 * @date 2019-04-22 10:34
 **/
public class StandardServer extends LifeCycleBase implements Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(StandardServer.class);

    private int port = 0;

    private Service[] services = new Service[0];
    private final Object servicesLock = new Object();


    @Override
    protected void startInternal() {
        LOGGER.info("StandardServer start");

        // 启动所有的services
        synchronized (servicesLock) {
            for (Service service : services) {
                service.start();
            }
        }
    }

    @Override
    protected void stopInternal() {
        LOGGER.info("StandardServer stop");
    }

    @Override
    protected void destroyInternal() {
        LOGGER.info("StandardServer destroy");
    }

    @Override
    public void setPort(int port) {
        this.port = port;
    }

    @Override
    public int getPort() {
        return port;
    }

    public void addService(Service service) {
        service.setServer(this);

        synchronized (servicesLock) {
            Service[] newServices = new Service[services.length + 1];
            System.arraycopy(services, 0, newServices, 0, services.length);
            newServices[services.length] = service;

            services = newServices;
        }
    }
}
